package guard

import (
	"errors"
	"github.com/gin-gonic/gin"
	"strconv"
	"strings"
)

type SignInParam struct {
	Account  string `json:"account"`
	Password string `json:"password"`
}

type SignInParamGuard struct{}

func SignIn() *SignInParamGuard {
	return new(SignInParamGuard)
}

func (p SignInParam) GetAccountType() string {
	if strings.Contains(p.Account, "@") {
		return "email"
	}
	acc, _ := strconv.Atoi(p.Account)
	if len(p.Account) == 11 && 10000000000 < acc && acc < 99999999999 {
		return "phone"
	}
	return "name"
}

func (a *SignInParamGuard) Guard(c *gin.Context) (interface{}, error) {

	var l SignInParam

	if err := c.BindJSON(&l); err != nil {
		return nil, errors.New("参数错误")
	}

	return l, nil
}

func GetSignInParam(c *gin.Context) SignInParam {
	return c.MustGet("param").(SignInParam)
}

type SignUpParam struct {
	Email    string `json:"email"`
	Name     string `json:"name"`
	Password string `json:"password"`
	//Phone    string `json:"phone"`
	//Code     string `json:"code"`
	PasswordConfirmation string `json:"password_confirmation"`
}

type SignUpParamGuard struct{}

func SignUp() *SignUpParamGuard {
	return new(SignUpParamGuard)
}

func (a *SignUpParamGuard) Guard(c *gin.Context) (interface{}, error) {

	var l SignUpParam

	if err := c.BindJSON(&l); err != nil {
		return nil, errors.New("参数错误")
	}

	if l.Password != l.PasswordConfirmation {
		return nil, errors.New("两次输入密码不一致")
	}

	if len(l.Password) < 10 {
		return nil, errors.New("密码长度太短了，最少10位")
	}

	return l, nil
}

func GetSignUpParam(c *gin.Context) SignUpParam {
	return c.MustGet("param").(SignUpParam)
}

type UniqueParam struct {
	Type  string `json:"type"`
	Value string `json:"value"`
}

type UniqueParamGuard struct{}

func Unique() *UniqueParamGuard {
	return new(UniqueParamGuard)
}

func (a *UniqueParamGuard) Guard(c *gin.Context) (interface{}, error) {

	var l UniqueParam

	if err := c.BindJSON(&l); err != nil {
		return nil, errors.New("参数错误")
	}

	return l, nil
}

func GetUniqueParam(c *gin.Context) UniqueParam {
	return c.MustGet("param").(UniqueParam)
}
